package com.lzw.cpvideoplayer.mvp.model;


import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;
import com.lzw.cpvideoplayer.data.HeadData;
import com.lzw.cpvideoplayer.data.cHeadData;
import com.lzw.cpvideoplayer.mvp.view.LoadDiaLog;

import java.io.IOException;

import androidx.annotation.NonNull;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LoadHttpData {
    private static final String TAG = "LoadHttpData";
    private static LoadHttpData load;
    public static boolean isLoadData = false;
    public static LoadHttpData getInstance(){
        if(load==null){
            load = new LoadHttpData();
        }
        return load;
    }

    public  void LoadVideoData(String url, Handler handler, Context context,int what){
        if(isLoadData){
            isLoadData = false;
        }
        Log.e(TAG, "LoadVideoData: " );
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e("搜索数据请求失败", "onFailure: "+e.getMessage());
                LoadDiaLog.getInstance(context).onLoadDismiss();
                Message msg = new Message();
                msg.what = 3;
                handler.sendMessage(msg);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
               Message msg = new Message();
                Gson gson = new Gson();
                String json = response.body().string();
                if(!isLoadData){
                    if(what == 1){
                        HeadData headData = gson.fromJson(json, HeadData.class);
                        msg.obj = headData;
                        Log.e(TAG, "onResponse: "+headData.getMsg());
                        msg.what = 1;

                    }else {
                        cHeadData headData = gson.fromJson(json, cHeadData.class);
                        msg.obj = headData;
                        Log.e(TAG, "onResponse: "+headData.getMsg());
                        msg.what = 2;

                    }
                }else {
                    isLoadData = false;
                }


                handler.sendMessage(msg);
            }
        });

    }
}
